use std::io::Cursor;

use rusqlite::Connection;

use crate::{Header, IndexTag, RPMError};

#[test]
pub fn test_db() {
    let path = "test_assets/rpmdb.sqlite";
    let conn = Connection::open(path).unwrap();
    let start = SystemTime::now();
    match get_pkg_headers_by_pkg_name(&conn, "libgcc") {
        Ok(s) => match s {
            Some(n) => {
                dbg!(n.get_conflicts().unwrap());
                // dbg!(n.get_arch().unwrap());
            }
            None => {}
        },
        Err(e) => {
            dbg!(e);
        }
    };
    // dbg!(heads.get_arch());
    let end = SystemTime::now().duration_since(start).unwrap();
    dbg!(end);
}
#[inline]
pub fn get_pkg_headers_by_pkg_name(
    conn: &Connection,
    pkg_name: &str,
) -> Result<Option<Header<IndexTag>>, RPMError> {
    let mut stmt = conn
        .prepare(
            "SELECT Packages.blob
            from Packages INNER JOIN Name on Packages.hnum=Name.hnum
            WHERE  Name.key= ?1",
        )
        .unwrap();
    let res = stmt.query_and_then([pkg_name], |row| row.get::<_, Vec<u8>>(0))?;
    let mut v = Vec::new();
    for ele in res {
        v.push(parse_pkg_blob_to_header(ele?.as_mut())?);
    }
    Ok(v.pop())
}
// #[inline]
// pub fn get_installed_pkg_headers_by_provide_name(
//     conn: &Connection,
//     provide_name: &str,
// ) -> Result<Option<Header<IndexTag>>, RPMError> {
//     let mut stmt = conn.prepare(
//         "SELECT Packages.blob
//         FROM Packages INNER JOIN Providename on Packages.hnum=Providename.hnum
//         WHERE Providename.key=?1",
//     )?;
//     let res = stmt.query_and_then([provide_name], |row| row.get::<_, Vec<u8>>(0))?;
//     let mut v = Vec::new();
//     for ele in res {
//         v.push(parse_pkg_blob_to_header(ele?.as_mut())?);
//     }
//     Ok(v.pop())
// }
#[inline]
pub fn parse_pkg_blob_to_header(blob: &mut Vec<u8>) -> Result<Header<IndexTag>, RPMError> {
    let mut buf = vec![0x8e, 0xad, 0xe8, 0x01, 0x00, 0x00, 0x00, 0x00];
    buf.append(blob);
    let mut input = Cursor::new(buf);
    Header::<IndexTag>::parse(&mut input)
}
// SELECT  Packages .blob  from  Packages  INNER JOIN Name on  Packages.hnum=Name.hnum  WHERE  Name.key="libgcc"
